/**
 * Created by Administrator on 2015/11/6 0006.
 */

//var Mongodb = require('../server/Mongo');
var DB = require('../server/CRUD');
var rest = require('rest');
var mime = require('rest/interceptor/mime');
var client = rest.wrap(mime, {mime: 'application/json'});
var logger = require('../utils/logger').logger
var utils = require('./Utils.js');

Menu = new DB("menu");
DB = new DB("video");

exports.register = function (app) {
    // 获取视频列表


    var getUserToken = function (code) {
        logger.info("appid:" + app.appid);
        logger.info("secret:" + app.secret);
        var url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + app.appid + "&secret=" + app.secret + "&code=" + code + "&grant_type=authorization_code"
        var q = rest(url).then(function (data) {
            var data = JSON.parse(data.entity);
            var openid = data.openid;
            logger.info(data);
            return openid;
        });
        return q;
    }

    var getUserGroupId = function (openid) {
        logger.info("openid:" + openid);
        q = app.locals.getToken().then(function (token) {
            var url = "https://api.weixin.qq.com/cgi-bin/groups/getid?access_token=" + token.value;
            var REQ_HEADERS = {
                'Content-Type': 'application/x-www-form-urlencoded'
            };
            var data = {
                openid: openid.toString()
            }
            logger.info("url:" + url);
            var q = client({method: "POST", path: url, entity: data}).then(function (data) {
                var val = data.entity
                var groupId = val.groupid
                logger.info("groupId：" + groupId);
                return groupId;
            })
            return q;
        })
        return q;
    }

    var getAccessToken = function () {
        q = app.locals.getToken()
        return q;
    }

    app.get("/video", function (req, res, next) {
        // TODO:vip
        var code = req.query.code;
        logger.info("code:" + code);

        var build = function () {
            var groupid = req.query.groupid
            var data = {}
            if (groupid) {
                data = {
                    groupid: groupid
                }
            }
            DB.read(data, function (list) {
                res.render("video", {
                    title: "VIP视频",
                    list: list.items
                })
            });
        }

        var toVideo = function (data) {
            logger.info(data);
            logger.info("get group id3 :" + data);
            if (data == 2) {
                build()
            } else {

                res.render("bevip", {
                    title: "您没有权限，需成为VIP",
                })
            }
        }
        getUserToken(code).then(getUserGroupId).then(toVideo).catch(function () {

            res.render("bevip", {
                title: "您没有权限，需成为VIP",
            })
        });
    });

    // 获取视频详情
    app.get("/video/:id", function (req, res, next) {
        // TODO:vip
        var id = req.params.id;
        groupid = req.signedCookies.groupid;
        if (groupid) {
            DB.read({_id: DB.toObjectId(id)}, function (list) {
                res.render("video-detail", {
                    title: "VIP视频",
                    video: list.items[0]
                })
            });
        } else {
            res.render("bevip", {
                title: "您没有权限，需成为VIP"
            })
        }
    });

    // 管理视频
    app.get("/manage-video", function (req, res, next) {
        username = req.signedCookies.username;
        if (username) {
            var groupid = req.query.groupid
            var data = {}
            if (groupid) {
                data = {
                    groupid: groupid
                }
            }
            DB.read(data, function (list) {
                list.group = app.getVip();
                console.log(list);
                res.render("manage-video", {
                    title: "管理视频",
                    list: list
                })
            })
        } else {
            res.redirect("/sign-in");
        }
    })

    app.post("/upload5", function (req, res, next) {
        if (req.files) {
            var results = {};
            for (var f in req.files) {
                results[f] = {
                    path: req.files[f].name
                }
            }
            console.log(results)
            res.json(results);
        } else {
            return res.status(400).end()
        }
    })

    app.post("/upload-video-image", function (req, res, next) {
        console.log(req.files)
        if (req.files) {
            var url = null
            for (var f in req.files) {
                url = req.files[f].name
            }
            var r ={
                state: "SUCCESS",
                url: url
            }
            console.log(r)
            res.writeHead(200, {"Content-Type": "text/html"});
            res.write(JSON.stringify(r));
            res.end();
        } else {
            return res.status(400).end()
        }
    })

    // 添加视频页面
    app.get("/add-video", function (req, res, next) {
        username = req.signedCookies.username;
        if (username) {
            var id = req.query.id
            if (id) {
                DB.read({_id: DB.toObjectId(id)}, function (list) {
                    res.render("add-video", {
                        title: "添加视频",
                        group: app.getVip(),
                        video: list.items[0]
                    })
                })
            } else {
                res.render("add-video", {
                    title: "添加视频",
                    group: app.getVip()
                })
            }
        } else {
            res.redirect("/sign-in");
        }
    })

    // 添加视频
    app.post("/manage-video", function (req, res, next) {
        username = req.signedCookies.username;
        if (username) {
            var video = req.body.video
            var id = video.id
            if (id){
                delete video["id"]
                DB.update({_id:DB.toObjectId(id)}, video, function(r){
                    res.json(r);
                })
            }else{
                delete video["id"]
                DB.create(video, function (r) {
                    res.json(r);
                })
            }
        } else {
            res.json({message: "signin"});
        }
    })


    // 删除视频
    app.post("/delete-video/:id", function (req, res, next) {
        var id = req.params.id
        DB.deleteData({_id: DB.toObjectId(id.substring(1, id.length - 1))}, function (status) {
            res.json(status);
        })
    })
}